from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from home.models import UserModel


def get_user(message):
    """
    多条件认证
    :param message:
    :return:
    """
    user = UserModel.objects.filter(Q(username=message) | Q(phone=message) | Q(email=message)).first()
    return user


class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        user = get_user(username)
        if user and user.check_password(password) and self.user_can_authenticate(user):
            return user
